package com.news.web.servlet.news;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.news.entity.User;
import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;

/**
 * Servlet implementation class NewsLogInservlet
 */
@WebServlet("/NewsLogInServlet")
public class NewsLogInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取传入数据
        String userName = request.getParameter("userName");
        String userPass = request.getParameter("userPass");
        
        //获取session
     	HttpSession session = request.getSession();

        // 判断数据是否为空
        if (userName == null || userPass == null || "".equals(userName) || "".equals(userPass)) {
        	session.setAttribute("logInUser", null);
            request.getRequestDispatcher("logIn.jsp").forward(request, response);
            return; // 转发后立即返回，防止继续执行后续代码
        }
        
        // 创建User类
        User user = new User();
        user.setUserName(userName);
        user.setUserPass(userPass);
        
        // 创建UserService实例
     	UserService userService = new UserServiceImpl();
     	User logInUser = userService.selectUser(userName, userPass);
     	
     	
     	// 判断是否有这个用户,由于后续需要使用user，所以使用session
        if (logInUser == null) {
        	request.setAttribute("logInUser", null);
            request.getRequestDispatcher("logIn.jsp").forward(request, response);
            return; // 转发后立即返回，防止继续执行后续代码
        } else {
        	//存入session
        	session.setAttribute("userName", userName);
        	session.setAttribute("userPass", userPass);
        	request.setAttribute("loginUser", logInUser);
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return; // 转发后立即返回，防止继续执行后续代码
        }
     	
	}

}
